package com.yicong.ants.ui.me.recommend;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.ShareBean;
import com.yicong.ants.databinding.DialogShareLayout2Binding;
import com.yicong.ants.databinding.DialogShareLayoutBinding;
import com.yicong.ants.databinding.ShareActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.holder.GlideRoundTransform;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.AppUtils;
import com.yicong.ants.utils.BitmapUtils;
import com.yicong.ants.utils.CodeCreator;
import com.yicong.ants.utils.FileHelper;
import com.yicong.ants.utils.ShareUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cchao
 * @version 2019-05-28.
 */
public class ShareActivity extends BaseTitleBarActivity<ShareActivityBinding> implements View.OnClickListener {

    String mQrUrl;
    Bitmap bitmap;

    @Override
    protected int getLayout() {
        return R.layout.share_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleBarVisible(false);
        AppHelper.transStatus(getWindow());
        mDataBind.setClick(this);

        mDataBind.mScrollView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                mDataBind.layoutGroup.setMinimumHeight(v.getHeight());
            }
        });
        onLoadData();
    }

    private void initDrawView() {
//        int containerW = (int) (UiHelper.getScreenWidth() * 0.8f);
//        int containerH = (int) (containerW * 1.77f);
//        int qrW = (int) (containerW * 0.34f);
//        int marginBottom = (int) (containerW * 1.77f * 0.14f);
//        UiHelper.updateLayoutParams(mDataBind.image, containerW, containerH);

        //二维码
//        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap-xxhdpi.ic_launcher2);
//        Bitmap qrCodeBitmap = CodeCreator.createQRCode(mQrUrl, qrW, qrW, logo);
//        mDataBind.qrField.setImageBitmap(qrCodeBitmap);

        // set params
//        ViewGroup.MarginLayoutParams paramsMargin = (ViewGroup.MarginLayoutParams) mDataBind.qrField.getLayoutParams();
//        paramsMargin.width = qrW;
//        paramsMargin.height = qrW;
//        paramsMargin.bottomMargin = marginBottom;
//        mDataBind.qrField.setLayoutParams(paramsMargin);
        mDataBind.image.setOnLongClickListener(v -> {
            BitmapDrawable drawable = (BitmapDrawable) mDataBind.image.getDrawable();
            FileHelper.saveViewToDirPic(thisActivity, drawable.getBitmap());
            return true;
        });

        Glide.with(this).asBitmap()
                .load(UserManager.getUserBean()
                        .getAvatar()).override(200, 200)
                .error(R.mipmap.ic_launcher2)
                .centerCrop()
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        GlideRoundTransform transform = new GlideRoundTransform(13, ContextCompat.getColor(ShareActivity.this, R.color.white), 2);
                        Bitmap bitmap = CodeCreator.createQRCode(mQrUrl, 236, 236, transform.roundCrop(resource));
                        drawQrImage(bitmap);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void drawQrImage(Bitmap qrBitmap) {
        Paint paint = new Paint();

        Bitmap bitmap = Bitmap.createBitmap(654, 896, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        Matrix matrix = new Matrix();
        Bitmap bp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image_root);
        float m = 654f / bp.getWidth();
        matrix.reset();
        matrix.postScale(m, m);
        canvas.drawBitmap(bp, matrix, paint);
        canvas.drawBitmap(qrBitmap, 211, 602, paint);

        mDataBind.image.setImageBitmap(bitmap);
    }

    @Override
    protected void onLoadData() {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("uid", UserManager.getUserId());
        addSubscribe(RetrofitHelper.getApis().recommendUrl(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    mQrUrl = respBean.getData();
                    initDrawView();
                }, RxHelper.getHideProgressConsumer(this)));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.copy:
                try {
                    //获取剪贴板管理器
                    if (StringHelper.isEmpty(mQrUrl)) {
                        return;
                    }
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 创建普通字符型ClipData
                    ClipData mClipData = ClipData.newPlainText("Label", mQrUrl);
                    // 将ClipData内容放到系统剪贴板里。
                    cm.setPrimaryClip(mClipData);
                    UiHelper.showToast("内容已复制");
                } catch (Exception e) {
                    Logs.logException(e);
                }
                break;
            case R.id.recommend_rule_field:

                break;
            case R.id.back:
                onBackPressed();
                break;

            case R.id.wx_share:
                if (StringHelper.isEmpty(mQrUrl)) {
                    return;
                }
//                bitmap = BitmapUtils.loadView2Bitmap(mDataBind.image);
                bitmap = ((BitmapDrawable) mDataBind.image.getDrawable()).getBitmap();
                UMImage image = new UMImage(this, bitmap);
                Dialog dialog = new AlertDialog.Builder(this).create();
                DialogShareLayout2Binding mBind = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_share_layout2, null, false);
                mBind.shareWx.setOnClickListener(v1 -> {
                    dialog.cancel();
                    ShareUtils.UMShareImage(thisActivity, SHARE_MEDIA.WEIXIN, image);
                });
                mBind.shareWxcircle.setOnClickListener(v12 -> {
                    dialog.cancel();
                    ShareUtils.UMShareImage(thisActivity, SHARE_MEDIA.WEIXIN_CIRCLE, image);
                });
                mBind.shareYchat.setOnClickListener(v13 -> {
                    if (!AppUtils.isInstallByread(Constants.YChat_package_name)) {
                        UiHelper.showToast("您还没下载蚁聊");
                        return;
                    }
                    ShareBean bean = new ShareBean().setTitle("推广好友").setDesc("免费旅游 说走就走！").setImage(UserManager.getUserBean().getAvatar()).setLink(mQrUrl);
                    ShareUtils.shareContent(this, bean);
                    dialog.cancel();
                });
                mBind.close.setOnClickListener(view -> dialog.cancel());
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
                Dialogs.requestDialogWidth90(dialog, mBind.getRoot());
                break;
        }
    }
}
